const instance = require('../request/index')
const getHotKeyword = require('./getHotKeyword/index')
const getSuggest = require('./getSuggest/index')
const getPic = require('./getPic/index')
class Crawler {
    constructor() {
    }

    /**
     * @desc 根据关键词抓取图片
     * @param keyword
     * @returns {Promise<*[]>}
     */

    getPic(keyword){
        return getPic(keyword)
    }

    /**
     *
     */
    getSuggest(keyword){
        return getSuggest(keyword)
    }

    /**
     * @description 获取目标地址的 chunks （网页内容）
     * @param url
     * @param method
     * @returns {Promise<string>}
     */
    getChunks(url, method) {
        return instance({
            url: url,
            method: method || 'get'
        })
    }

    getHotKeyword(){
        return getHotKeyword()
    }

    /**
     *
     * @param keyword
     * @returns {Promise<string>}
     * @tips https://cn.bing.com/news/NewsAnswerV2CarouselAjax?q=%E5%A6%87%E4%BA%A7%E7%A7%91
     */
    searchByBingHome(keyword) {
        let url = `https://cn.bing.com/search?q=${encodeURI(keyword)}`
        return this.getChunks(url, 'get')
    }

    /**
     * @desc 原生方法获取源页面buffer
     * @param url
     * @param callback
     */
    getDomStrByCheerio(url, callback) {
        let chunks = []
        let isHttps = (function (url) {
            if (url.indexOf('http') === -1) {
                console.error('必须包含协议头！，请检查您传入的url')
            } else {
                return url.indexOf('https://') !== -1
            }
            return false
        })(url)
        let request = isHttps ? https : http
        request.get(url, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            agent: request.globalAgent,
        }, function (res) {
            res.on("data", chunk => {
                chunks.push(chunk)
            })
            res.on('end', () => {
                console.log(`${url}请求已结束！`)
                typeof callback === 'function' && callback(chunks.concat())
            })
        })
    }
}

module.exports = crawler = new Crawler()